from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from ui.main import Ui_MainWindow
from ui.analysis import Ui_Form
from person import PersonWidget
from CameraListView import CameraListView

import torch
import argparse
import cv2
import numpy as np
import imutils
import copy
import os
import time
import logging
import threading

filename = '%s/log/%s.log' % (os.getcwd(),
                              time.strftime("%Y%m%d", time.localtime()))
logging.basicConfig(level=logging.INFO,  # 控制台打印的日志级别
                    filename=filename,
                    filemode='a',  # 模式，有w和a，w就是写模式，每次都会重新写日志，覆盖之前的日志
                    format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'
                    )
logger = logging.getLogger(__name__)

class MainWindow(QMainWindow, Ui_MainWindow):

    local_path = './packages'
    signal_txt = pyqtSignal(str)
    textBrowser_signal = pyqtSignal(list)

    analysis_signal = pyqtSignal(np.ndarray, str)

    img_show_signal = pyqtSignal(np.ndarray)

    thermal_frame = None
    info = []

    person_widgets = []

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setWindowState(Qt.WindowMaximized)
        self.setWindowIcon(QIcon(':icons/images_rc/app.png'))
        self.setWindowTitle("辐射场升级软件")

        self.listView_cameras = CameraListView()
        self.verticalLayout_cameras.addWidget(self.listView_cameras)

        self.pushButton_open_camera.clicked.connect(self.openCamera)
        self.pushButton_close_camera.clicked.connect(self.closeCamera)
        self.img_show_signal.connect(self.showImg)

        self.updateCamera()

    def closeEvent(self, event):
        print("关闭程序...")
        self.closeCamera()
        time.sleep(1)
        # sys.exit(app.exec_())

    def get_thresh(self, src):
        """  获取阈值 ，通过图像的均值和标准偏差获取阈值 """
        gray, mat_mean, mat_stddev = 0, 0, 0
        gray = cv2.cvtColor(src,  cv2.COLOR_RGB2GRAY)
        (mat_mean, mat_stddev) = cv2.meanStdDev(gray)
        thresh = (5 / 4) * (mat_mean[0][0] + mat_stddev[0][0])
        return thresh

    def showImg(self, img):
        # 提取图像的通道和尺寸，用于将OpenCV下的image转换成Qimage
        if len(img.shape) == 3:
            height, width, channel = img.shape
            bytesPerline = 3 * width
            QImg = QImage(img.data, width, height, bytesPerline, QImage.Format_RGB888).rgbSwapped()
        elif len(img.shape) == 2: # 灰度图
            height, width = img.shape
            bytesPerline = width
            QImg = QImage(img.data, width, height, bytesPerline, QImage.Format_Indexed8)
        else:
            return
        # 将QImage显示出来
        self.label_img.setPixmap(QPixmap.fromImage(QImg))

    def updateCamera(self):
        cnt = 0
        for device in range(0, 5):
            stream = cv2.VideoCapture(device)

            grabbed = stream.grab()
            print(device)
            stream.release()
            if not grabbed:
                break

            self.listView_cameras.addCamera(camera={"name": str(cnt), "resize": 1})
            self.gridLayout_camera.addWidget(self.listView_cameras.items[cnt].person_widget, int(cnt // 2), int(cnt // 2) + (cnt % 2), 1, 1)

            cnt = cnt + 1
        return cnt

    def openCamera(self):
        try:
            self.textBrowser.append("启动摄像头...")
        except Exception as e:
            self.textBrowser.append("摄像头打开失败: %s" % e)
            return None

    def closeCamera(self):
        # for n in self.person_widgets.keys():
        #     self.person_widgets[n].stop()
        self.textBrowser.append("关闭摄像头...")

    
if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    app.exec_()
